<!DOCTYPE html>
<html>
<head>
  <title>算法可视化示例-冒泡排序</title>
  <style>
    #canvas {
      border: 1px solid black;
    }
  </style>
</head>
<body>
  <h1>算法可视化示例 - 冒泡排序</h1>

  <canvas id="canvas" width="800" height="400"></canvas>

  <script>
    // 获取 Canvas 元素
    const canvas = document.getElementById("canvas");
    const context = canvas.getContext("2d");

    // 冒泡排序算法
    async function bubbleSort(arr) {
      const len = arr.length;
      for (let i = 0; i < len - 1; i++) {
        for (let j = 0; j < len - i - 1; j++) {
          // 交换元素
          if (arr[j] > arr[j + 1]) {
            [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
          }
          // 绘制当前状态
          draw(arr, j, j + 1);
          await sleep(100); // 等待一段时间，以便观察动画效果
        }
      }
    }

    // 绘制数组元素
    function draw(arr, index1, index2) {
      context.clearRect(0, 0, canvas.width, canvas.height);
      const barWidth = canvas.width / arr.length;

      for (let i = 0; i < arr.length; i++) {
        const x = i * barWidth;
        const height = arr[i] * 10;
        const y = canvas.height - height;
        
        // 绘制矩形条
        context.fillStyle = (i === index1 || i === index2) ? "red" : "gray";
        context.fillRect(x, y, barWidth, height);
        
        // 绘制数字
        context.fillStyle = "white";
        context.font = "12px Arial";
        context.fillText(arr[i], x + barWidth / 2 - 6, y + height / 2 + 4);
      }
    }

    // 辅助函数：等待一段时间
    function sleep(ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
    }

    // 初始化数组并执行冒泡排序
    const array = [6, 3, 8, 2, 9, 1, 5, 7, 4];
    bubbleSort(array);
  </script>
</body>
</html>
